using System.Net;
using System.Net.Sockets;
using Microsoft.AspNetCore.Http;

namespace Crux.Core.Mvc.Utils;
/// <summary>
/// 
/// </summary>
public static class IPHelper
{
    /// <summary>
    /// 
    /// </summary>
    public static string[] IpHeaders = ["X-Real-IP", "X-Forwarded-For", "REMOTE_ADDR"];
    /// <summary>
    /// 
    /// </summary>
    /// <param name="httpContext"></param>
    /// <returns></returns> 
    public static string? GetIpAddress(
        this HttpContext httpContext)
    {
        foreach (var header in IpHeaders)
        {
            if (!httpContext.Request.Headers.TryGetValue(header, out var ipAddressStringValue))
            {
                continue;
            }

            var ipAddress = ipAddressStringValue.ToString();

            if (string.IsNullOrEmpty(ipAddress))
            {
                continue;
            }

            var ips = ipAddress.Split(',', (char)StringSplitOptions.RemoveEmptyEntries)
                              .Select(s => s.Trim());

            foreach (var ip in ips)
            {
                if (!IPAddress.TryParse(ip, out var address) ||
                    address.AddressFamily is not AddressFamily.InterNetwork
                     and not AddressFamily.InterNetworkV6)
                {
                    continue;
                }

                return ip;
            }
        }

        if (httpContext?.Connection?.RemoteIpAddress is null)
        {
            return string.Empty;
        }

        return httpContext?.Connection?.RemoteIpAddress?.ToString();
    }

}